package net.suncaper.mvc.mapper.impl;

import net.suncaper.mvc.mapper.PermissionMapper;
import net.suncaper.mvc.model.domain.Permission;
import net.suncaper.mvc.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Permission表数据库访问接口实现类
 */
public class PermissionMapperImpl implements PermissionMapper {
    private static final QueryRunner RUNNER = new QueryRunner();

    /**
     * 新增权限信息
     *
     * @param permission 权限信息
     * @return 新增结果
     */
    @Override
    public boolean insertPermission(Permission permission) {
        String sql = "INSERT INTO permission(permission_id, permission_name) VALUES (?, ?)";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    permission.getPermissionId(), permission.getPermissionName()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 根据权限ID查询权限信息
     *
     * @param permissionId 权限ID
     * @return 权限信息
     */
    @Override
    public Permission selectPermissionById(Integer permissionId) {
        String sql = "SELECT * FROM permission WHERE permission_id = ?";
        Connection connection = JDBCUtils.getConnection();
        Permission permission = null;
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1, permissionId);
            rs = ps.executeQuery();
            if (rs.next()) {
                permission = new Permission();
                permission.setPermissionId(rs.getInt("permission_id"));
                permission.setPermissionName(rs.getString("permission_name"));
                System.out.println("[selectPermissionById] permission_id=" + rs.getInt("permission_id") + ", permission_name=" + rs.getString("permission_name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return permission;
    }

    /**
     * 根据权限名称查询权限信息
     *
     * @param permissionName 权限名称
     * @return 权限信息
     */
    @Override
    public Permission selectPermissionByName(String permissionName) {
        String sql = "SELECT * FROM permission WHERE permission_name = ?";
        Connection connection = JDBCUtils.getConnection();
        Permission permission = null;
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, permissionName);
            rs = ps.executeQuery();
            if (rs.next()) {
                permission = new Permission();
                permission.setPermissionId(rs.getInt("permission_id"));
                permission.setPermissionName(rs.getString("permission_name"));
                System.out.println("[selectPermissionByName] permission_id=" + rs.getInt("permission_id") + ", permission_name=" + rs.getString("permission_name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return permission;
    }

    /**
     * 查询所有权限信息
     *
     * @return 权限列表
     */
    @Override
    public List<Permission> selectAllPermissions() {
        String sql = "SELECT * FROM permission";
        Connection connection = JDBCUtils.getConnection();
        List<Permission> permissions = new java.util.ArrayList<>();
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Permission permission = new Permission();
                permission.setPermissionId(rs.getInt("permission_id"));
                permission.setPermissionName(rs.getString("permission_name"));
                System.out.println("[selectAllPermissions] permission_id=" + rs.getInt("permission_id") + ", permission_name=" + rs.getString("permission_name"));
                permissions.add(permission);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return permissions;
    }

    /**
     * 更新权限信息
     *
     * @param permission 权限信息
     * @return 更新结果
     */
    @Override
    public boolean updatePermission(Permission permission) {
        String sql = "UPDATE permission SET permission_name = ? WHERE permission_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    permission.getPermissionName(), permission.getPermissionId()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 删除权限信息
     *
     * @param permissionId 权限ID
     * @return 删除结果
     */
    @Override
    public boolean deletePermission(Integer permissionId) {
        String sql = "DELETE FROM permission WHERE permission_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    permissionId
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 根据角色ID查询该角色拥有的权限列表
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public List<Permission> selectPermissionsByRoleId(Integer roleId) {
        String sql = "SELECT p.* FROM permission p JOIN role_permission rp ON p.permission_id = rp.permission_id WHERE rp.role_id = ?";
        Connection connection = JDBCUtils.getConnection();
        List<Permission> permissions = new java.util.ArrayList<>();
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1, roleId);
            rs = ps.executeQuery();
            while (rs.next()) {
                Permission permission = new Permission();
                permission.setPermissionId(rs.getInt("permission_id"));
                permission.setPermissionName(rs.getString("permission_name"));
                System.out.println("[selectPermissionsByRoleId] permission_id=" + rs.getInt("permission_id") + ", permission_name=" + rs.getString("permission_name"));
                permissions.add(permission);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return permissions;
    }

    /**
     * 根据用户ID查询该用户拥有的权限列表
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public List<Permission> selectPermissionsByUserId(String userId) {
        String sql = "SELECT DISTINCT p.* FROM permission p " +
                "JOIN role_permission rp ON p.permission_id = rp.permission_id " +
                "JOIN user_role ur ON rp.role_id = ur.role_id " +
                "WHERE ur.user_id = ?";
        Connection connection = JDBCUtils.getConnection();
        List<Permission> permissions = new java.util.ArrayList<>();
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, userId);
            rs = ps.executeQuery();
            while (rs.next()) {
                Permission permission = new Permission();
                permission.setPermissionId(rs.getInt("permission_id"));
                permission.setPermissionName(rs.getString("permission_name"));
                System.out.println("[selectPermissionsByUserId] permission_id=" + rs.getInt("permission_id") + ", permission_name=" + rs.getString("permission_name"));
                permissions.add(permission);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return permissions;
    }
} 